﻿#include "optioneditor.h"
#include "ui_optioneditor.h"

OptionEditor::OptionEditor(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::OptionEditor)
{
    ui->setupUi(this);

    saveFlag=0;
    model = new QStringListModel(this);
    ui->listView->setModel(model);
}

OptionEditor::~OptionEditor()
{
    delete ui;
}

bool OptionEditor::detect(const OptionType &type)
{
    _type=type;
    switch (_type) {
    case O_PROVIDER:
        _file=LST_PROVIDER;
        break;
    case O_CONTRACTOR:
        _file=LST_CONTRACTOR;
        break;
    case O_RECEIVER:
        _file=LST_RECEIVER;
        break;
    case O_EXPRESS:
        _file=LST_EXPRESS;
        break;
    case O_TRANSACTOR:
        _file=LST_TRANSACTOR;
        break;
    case O_LOGISTICS:
        _file=LST_LOGISTICS;
        break;
    }

    if(option.load(_file))
    {
        model->setStringList(option.getStringList());
        return true;
    }
    else
        return false;
}

void OptionEditor::on_btn_add_clicked()
{
    int row=model->rowCount();
    if(row == 0)
        return;

    QModelIndex last=model->index(row - 1);
    QString lastStr=model->data(last,0).toString();
    if(lastStr == OPT_TEXT)
        return;

    model->insertRow(row);
    QModelIndex index=model->index(row);
    model->setData(index,OPT_TEXT);

    ui->listView->setCurrentIndex(index);
    ui->listView->edit(index);
    saveFlag=-1;

    if(!ui->lbl_status->text().isEmpty())
        ui->lbl_status->clear();
}

void OptionEditor::on_btn_del_clicked()
{
    if(model->rowCount() == 0)
        return;

    if(model->rowCount() > 1)
    {
        int row=ui->listView->currentIndex().row();
        model->removeRow(row);
        saveFlag=-1;
    }
    else
        QMessageBox::warning(this,QStringLiteral("至少保留一项"),QStringLiteral("至少保留一项！"),
                             QMessageBox::Ok);

    if(!ui->lbl_status->text().isEmpty())
        ui->lbl_status->clear();
}

void OptionEditor::on_btn_save_clicked()
{
    if(model->rowCount() == 0)
        return;

    switch (saveFlag) {
    case 0:
        QMessageBox::warning(this,QStringLiteral("菜单未修改"),QStringLiteral("菜单未修改，无需保存！"),
                             QMessageBox::Ok);
        break;
    case -1:
        option.setStringList(model->stringList());
        if(option.save(_file))
        {
            saveFlag=1;
            emit reload(_type);
            accept();
        }
        else
            ui->lbl_status->setText(QStringLiteral("保存失败！"));
        break;
    case 1:
        QMessageBox::warning(this,QStringLiteral("新菜单未修改"),QStringLiteral("新菜单未修改，无需保存！"),
                             QMessageBox::Ok);
        break;
    }
}
